import { IBreadcrumb } from '@/base-ui/breadcrumb';
import menu from '@/router/main/system/menu/menu';
import type { RouteRecordRaw } from 'vue-router';

let firstMenu: any = null;

// 将后端取到的userMenus中type为2的url添加到路由中
export function mapMenustoRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = [];

  // 1.先去加载默认所有的routes
  const allRoutes: RouteRecordRaw[] = [];
  // 使用webpack内置的方法帮助加载文件夹
  // 参数：1文件夹路径，2true文件夹下的文件夹，3文件后缀,加载.ts结尾的文件
  const routeFiles = require.context('../router/main', true, /\.ts/);
  routeFiles.keys().forEach((key) => {
    // key就是相对于main文件夹下的ts文件的路径，例如./analysis/dashboard/dashboard.ts
    const route = require('../router/main' + key.split('.')[1]);
    allRoutes.push(route.default);
  });
  // 2.根据菜单获取添加需要的routes
  const _recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => route.path === menu.url);
        if (route) routes.push(route);
        if (!firstMenu) {
          firstMenu = menu;
        }
      } else {
        _recurseGetRoute(menu.children);
      }
    }
  };
  _recurseGetRoute(userMenus);

  return routes;
}

export function pathMapBreadcrumbs(userMenus: any[], currentPath: string) {
  const breadcrumbs: IBreadcrumb[] = [];
  pathMapToMenu(userMenus, currentPath, breadcrumbs);
  return breadcrumbs;
}

// /main/system/role  -> type === 2 对应menu
export function pathMapToMenu(
  userMenus: any[],
  currentPath: string,
  breadcrumbs?: IBreadcrumb[]
): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapToMenu(menu.children ?? [], currentPath);
      if (findMenu) {
        breadcrumbs?.push({ name: menu.name });
        breadcrumbs?.push({
          name: findMenu.name
        });
        return findMenu;
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu;
    }
  }
}

// 按钮权限
export function mapMenusToPermissions(userMenus: any[]) {
  const permission: string[] = [];

  const _recurseGetPermission = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 1 || menu.type === 2) {
        _recurseGetPermission(menu.children ?? []);
      } else if (menu.type === 3) {
        permission.push(menu.permission);
      }
    }
  };

  _recurseGetPermission(userMenus);
  return permission;
}

export function menuMapLeafKeys(menuList: any[]) {
  const leftKeys: number[] = [];

  const _recurseGetLeaf = (menuList: any[]) => {
    for (const menu of menuList) {
      if (menu.children) {
        _recurseGetLeaf(menu.children);
      } else {
        leftKeys.push(menu.id);
      }
    }
  };

  _recurseGetLeaf(menuList);

  return leftKeys;
}

export { firstMenu };
